const router = require('koa-router')()
const path=require('path')
const uploader=require('../utils/uploader')
const multer = require('koa-multer')
const config=require('./config')

const baseUrl=config.baseUrl
const sys_env=config.sys_env




//设置上传图片配置
var storage = multer.diskStorage({
    //文件保存路径
    destination: function (req, file, cb) {
        cb(null, path.join(__dirname, '../public/uploads/'))
    },
    //修改文件名称
    filename: function (req, file, cb) {
        var fileFormat = (file.originalname).split(".");
        cb(null,Date.now() + "." + fileFormat[fileFormat.length - 1]);
    },
    //文件时长

})

//加载配置
var upload = multer({ storage: storage });



//上传图片，语音
router.post('/api/uploadImg',upload.single('file'),async(ctx,next)=>{
    let img=ctx.req.file

    let pathArr=[]

    if(sys_env=="windows"){
        pathArr=img.path.split(`public\\uploads\\`)  //windows系统
    }
    else if(sys_env=="linux"){
        pathArr=img.path.split(`public/uploads/`)  //linux系统
    }


    let path=baseUrl+`/uploads/`+pathArr[1]

    ctx.body={
        code:0,
        data:path
    }
})



//获取文件上传到七牛的token
router.post('/api/uploadToken',async(ctx,next)=>{
    let filename=ctx.request.body.filename
    let res=await uploader.uploadToken(filename)

    ctx.body={
        code:0,
        data:res
    }
})



//对应建伟上传图片到七牛,获取token
router.post('/api/getXueShengQiNiuToken',async(ctx,next)=>{
    let filename=ctx.request.body.filename
    let res=await uploader.uploadTokenForXuesheng(filename)

    ctx.body={
        code:0,
        data:res
    }
})


//上传图片，语音
//上传到七牛,经过服务器中转，然后上传到七牛
router.post('/api/uploadImgToQiNiu',async(ctx,next)=>{

    let url=await  uploader.uploadImage(ctx,next)

    ctx.body={
        code:0,
        data:url
    }

})



//上传语音
router.post('/api/uploadRecordVoice',upload.single('file'),async(ctx,next)=>{
    let voice=ctx.req.file

    let duration=ctx.req.body.duration

    let pathArr=[]

    if(sys_env=="windows"){
        pathArr=voice.path.split(`public\\uploads\\`)  //windows系统
    }
    else if(sys_env=="linux"){
        pathArr=voice.path.split(`public/uploads/`)  //linux系统
    }

    let path=baseUrl+`/uploads/`+pathArr[1]

    ctx.body={
        code:0,
        data:path
    }
})




module.exports = router
